#!/usr/bin/env python
from kivy.metrics import dp
from kivy.logger import Logger
from kivy.uix.button import Button
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.popup import Popup
from kivy.uix.scrollview import ScrollView

from amgineirc.view.messageView import MessageView
from amgineirc.viewModel.channels.defaultViewModel import DefaultViewModel

__all__ = ['ConnectPopup', 'DefaultView']

class ConnectPopup(Popup, MessageView):
    
    def __init__(self, vm_on_press_handler):
        self.vm_on_press_handler = vm_on_press_handler
        Popup.__init__(self,
                       title=DefaultView.connect_command,
                       content=FloatLayout(size=(400,500)),
                       size_hint=(None, None),
                       size=(400, 500))
        MessageView.__init__(self)
        self._listview = _DefaultListView(self.w_on_press_handler,
                                          pos_hint={'x':0.0,'y':0.1},
                                          size_hint=(1.0, 0.9))
        self.content.add_widget(self._listview)
        self.content.add_widget(Button(text='Cancel',
                                       size_hint=(1.0, 0.1),        
                                       pos_hint={'x':0.0,'y':0.0},
                                       on_press=self.dismiss))

    def w_on_press_handler(self, instance):
        self.dismiss()
        self.vm_on_press_handler(instance)
        
    def vm_add_domain(self, domain, port, secure, nick, nick_password):
        self._listview.log(domain, port, secure, nick, nick_password)
        

class _ServerRecordButton(Button):
    def __init__(self, domain, port, secure, nick, nick_password, **kargs):
        if 'text' in kargs:
            del(kargs['text'])
        kargs['markup'] = True
        kargs['size_hint'] = (1.0, None)
        kargs['height'] = dp(50)
        Button.__init__(self, **kargs)
        self.reset_text(domain, port, secure, nick, nick_password)
        
    def reset_text(self, domain, port, secure, nick, nick_password):
        self.domain = domain
        sec = '+' if secure else '-'
        pwd = '*' * len(nick_password)
        self.text = "[b]%s[/b] : %i %s [b]%s[/b] %s" % (domain, port, sec, nick, pwd)
            

class _DefaultListView(ScrollView):
    def __init__(self, server_record_on_press_handler, **kargs):
        kargs['do_scroll_x'] = False
        ScrollView.__init__(self, **kargs)
        # view model command handling method
        self.server_record_on_press_handler = server_record_on_press_handler
        # create a default grid layout with custom width/height
        self._layout = GridLayout(cols=1,
                                  size_hint=(1.0, None))
        # when we add children to the grid layout, its size doesn't change at
        # all. we need to ensure that the height will be the minimum required to
        # contain all the childs. (otherwise, we'll child outside the bounding
        # box of the childs)
        self._layout.bind(minimum_height=self._layout.setter('height'))
        self.add_widget(self._layout)
        
    def log(self, domain, port, secure, nick, nick_password):
        w = _ServerRecordButton(domain, port, secure, nick, nick_password,
                                on_press=self.server_record_on_press_handler)
        y = self.scroll_y
        self._layout.add_widget(w)
        # if the scroll view was scrolled to the end
        # then stay at the end
        if y == 1.0:
            self.scroll_y = y
        return w
        
    def add_cancel_button(self, window):
        self._layout.add_widget(Button(text='Cancel', on_press=window.dismiss))
    


class DefaultView(FloatLayout, MessageView):
    """a view for the domains page
        
        use bind_apply to bind the vm method to read and store the vars
        use bind_reset to bind the vm method to reset the vars

    """
    connect_command = 'Connect To A Server'
    
    def __init__(self, appdata, **kargs):
        FloatLayout.__init__(self, **kargs)
        MessageView.__init__(self)
        self._appdata = appdata
        # list of current domains
        self.connect_button = Button(text=self.__class__.connect_command,
                                                size_hint=(0.5, 0.2),
                                                pos_hint={'center_x':0.5, 'center_y':0.8},
                                                on_press=self.w_connect_button_handler)
        self.add_widget(self.connect_button)
        self.vm_connect_button_handler = lambda *largs : None
        # initialize the view model
        DefaultViewModel(self, appdata)

    # widget methods
            
    def w_connect_button_handler(self, instance):
        # the user has selected to connect
        if self.vm_connect_button_handler is not None:
            self.vm_connect_button_handler(instance)
